package com.syni.mdd.sjb.common.component.utils.common.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @className ApplicationContextHolder
 * @description TOO
 * @Author cfx
 * @DATE 2020/4/13 11:11
 * @VERSION 1.0
 **/
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    public static String RUN_LOCAL = "local";
    public static String RUN_DEV = "dev";
    public static String RUN_PREO = "preo";
    public static String RUN_PRO = "pro";

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }


    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static String getActiveProfile(){
        if(applicationContext != null) {
            String[] profiles = applicationContext.getEnvironment().getActiveProfiles();
            if (profiles.length > 0) {
                return applicationContext.getEnvironment().getActiveProfiles()[0];
            }
        }
        return null;
    }

    public static boolean checkRunProfile(String profile){
        String nowProfile = getActiveProfile();
        if(profile != null){
            return profile.equals(nowProfile);
        }
        return true;
    }

    public static boolean checkRunProfile(String... profiles){
        String nowProfile = getActiveProfile();
        if(profiles != null && profiles.length > 0){
            for(String profile : profiles) {
                if(profile.equals(nowProfile)){
                    return true;
                }
            }
        }
        return false;
    }

    public static Object getBean(String beanName){
        return ApplicationContextHolder.getApplicationContext().getBean(beanName);
    }

    public static <T> T  getBean(Class classes){
        T obj = (T) ApplicationContextHolder.getApplicationContext().getBean(classes);
        return obj;
    }

}
